package com.yn.xr.common.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**   
 * @description:一系列bean工具类
 * @fileName:BeanUtils.java 
 * @createTime:2015年3月23日 下午6:55:18  
 * @author:Wuwenyong
 * @version 1.0.0  
 *    
 */
public class BeanUtils
{
	/**   
	 * @function:  将实体转为map
	 * @param bean
	 * @return Map   
	 * @exception 
	 * @author:Wuwenyong  
	 * @since  1.0.0   
	*/
	public static Map bean2Map(Object bean){ 
        try
		{
			Class type = bean.getClass(); 
			Map returnMap = new HashMap(); 
			BeanInfo beanInfo = Introspector.getBeanInfo(type); 
			PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors(); 
			for (int i = 0; i< propertyDescriptors.length; i++) { 
			    PropertyDescriptor descriptor = propertyDescriptors[i]; 
			    String propertyName = descriptor.getName(); 
			    if (!propertyName.equals("class")) { 
			        Method readMethod = descriptor.getReadMethod(); 
			        Object result = readMethod.invoke(bean, new Object[0]); 
			        if (result != null && !"".equals(result.toString())) { 
			            returnMap.put(propertyName, result); 
			        } else { 
			            returnMap.put(propertyName,null);//属性值为空值处理为null 
			        } 
			    } 
			} 
			return returnMap;
		}
		catch (Exception e)
		{
			return new HashMap();
		} 
    } 
	
	/**   
	 * @function:  把对象的属性值转换成list结果集
	 * @param obj
	 * @return List<Object>   
	 * @exception 
	 * @author:Wuwenyong  
	 * @since  1.0.0   
	*/
	public static List<Object> renderObjValue (Object obj){
		List<Object> objData = new ArrayList<Object>();
		Field [] fields = obj.getClass().getDeclaredFields();
		if(fields == null || fields.length < 1) return null;
		try {
			for(int i=0; i<fields.length; i++){
				String fieldName = fields[i].getName();
				if("serialVersionUID".equals(fieldName) || fieldName.contains("_ignore_"))//忽略字段
					continue;
				StringBuffer getMethodName = new StringBuffer("get")
					.append(fieldName.substring(0, 1).toUpperCase())
					.append(fieldName.substring(1, fieldName.length()));
				Method getMethod = obj.getClass().getMethod(getMethodName.toString());
				Object tarValue = getMethod.invoke(obj);
				objData.add(tarValue);
			}
		} catch (Exception e) {
			return new ArrayList<Object>();
		} 
		return objData;
	} 
}
